package com.jcxy.filter;

import com.jcxy.pojo.Menu;
import com.jcxy.pojo.User;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/**
 * 控制器请求的拦截器，用于权限管理
 * 可放行：/loginController.do
 */
@WebFilter(filterName = "ActionPowerFilter",urlPatterns = "*.do")
public class ActionPowerFilter implements Filter {
    public void destroy() {
    }

    public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {

        HttpServletRequest request = (HttpServletRequest)req;
        HttpServletResponse response = (HttpServletResponse)resp;

        //获取请求url，从中截取资源路径
        String requestURI = request.getRequestURI();//请求路径：/菜单类型/方法名.do
        //截取菜单类型
        String powerTypeUrl = requestURI.substring(1,requestURI.indexOf("/",1));
        //可放行的请求url菜单类型
        String accessUrl = "loginController";
        //如果请求url不是可放行的url，则查询是否有权限
        if (!accessUrl.contains(powerTypeUrl)){
            //获取登录用户对象
            Object user = request.getSession().getAttribute("user");
            //如果user不为null才判断是否有权限
            if(user != null){

                //获取用户的菜单权限列表
                List<Menu> menuList = ((User) user).getRole().getMenuList();
                //遍历菜单权限列表，查看是否有权限
                boolean isAccess = false;
                for (Menu menu : menuList){
                    String menu_url = menu.getMenu_url();//菜单url：/父菜单名/菜单类型.jsp

                    //不判断父级菜单
                    if(!"#".equals(menu_url)){
                        //截取菜单类型
                        String menuType = menu_url.substring(menu_url.indexOf("/", 1) + 1, menu_url.lastIndexOf("."));

                        //如果有权限，将标志置为true，跳出循环
                        if (menuType.equals(powerTypeUrl)){
                            isAccess = true;
                            break;
                        }
                    }
                }
                if (isAccess){
                    //有权限，放行
                    chain.doFilter(req, resp);
                }else {
                    //没有权限，跳转到noPermission.jsp页面
                    response.sendRedirect("/jsp/noPermission.jsp");
                }
            }else{
                //没有登录user对象，跳转到noPermission.jsp页面
                response.sendRedirect("/jsp/noPermission.jsp");
            }
        }else {
            //请求url属于可放行的路劲，则放行
            chain.doFilter(req, resp);
        }
    }

    public void init(FilterConfig config) throws ServletException {

    }

}
